export function printMap(content, options) {
    const frameWindow = document.createElement('iframe');
    document.body.insertBefore(frameWindow, document.body.firstChild);
    const div = document.createElement('div');
    div.appendChild(content);
    return printFrame(frameWindow, div.innerHTML, options)
        .then(() => {
            frameWindow.remove();
            return Promise.resolve('close');
        })
        .catch((err) => {
            console.log('print error!');
            frameWindow.remove();
            return Promise.reject(err);
        });
}

function printFrame(frameWindow, content, options) {
    return new Promise((resolve, reject) => {
        const callPrint = () => {
            if (printed) return;
            printed = true;
            try {
                const targetWindow = frameWindow.contentWindow || frameWindow.contentDocument || frameWindow;
                targetWindow.focus();
                if (!targetWindow.document.execCommand('print', false, null)) {
                    targetWindow.print();
                }
            } catch (e) {
                frameWindow.print();
            }
            frameWindow.removeEventListener('load', callPrint); // 移除监听器
            resolve();
        };

        let printed = false;
        const printStyles = `  <style>
        @media print {
          img {
            max-width: 100% !important;
            height: auto !important;
            page-break-inside: avoid; /* 防止图片被分页截断 */
          }
          body { 
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      </style>`;
        try {
            const wdoc = frameWindow.contentDocument || frameWindow.document;
            if (options?.doctype) {
                wdoc.write(options.doctype + printStyles);
            }
            wdoc.write(content + printStyles);
            wdoc.close();
            frameWindow.addEventListener('load', callPrint);
            setTimeout(callPrint, options?.timeout ?? 750);
        } catch (err) {
            frameWindow.removeEventListener('load', callPrint);
            reject(err);
        }
    });
}
